package cn.cxy.myapplication

import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import cn.cxy.myapplication.annotation.TitleBar

open class BaseActivity : AppCompatActivity() {

    override fun setContentView(layoutResID: Int) {
        val titleBarAnnotation = javaClass.getAnnotation(TitleBar::class.java)
        if (titleBarAnnotation != null) {
            var linearLayout = LinearLayout(this)
            linearLayout.orientation = LinearLayout.VERTICAL

            addTitleBar(titleBarAnnotation, linearLayout)
            addOriginalView(layoutResID, linearLayout)

            super.setContentView(linearLayout)
        } else {
            super.setContentView(layoutResID)
        }
    }

    private fun addOriginalView(layoutResID: Int, linearLayout: LinearLayout) {
        var params = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )
        var contentView = LayoutInflater.from(this).inflate(layoutResID, null, false)
        linearLayout.addView(contentView, params)
    }

    private fun addTitleBar(titleBarAnnotation: TitleBar, linearLayout: LinearLayout) {
        val textView = TextView(this)
        titleBarAnnotation.value.let { textView.text = it }
        linearLayout.addView(textView)
    }
}